package com.zj.jdbc;

import com.zj.util.JdbcPropertyLoader;

import java.io.PrintWriter;
import java.sql.*;
import java.util.LinkedList;
import java.util.logging.Logger;
import javax.sql.DataSource;

/**
 * @ClassName: JdbcPool
 * @Description:编写数据库连接池
 * @author: 孤傲苍狼
 * @date: 2014-9-30 下午11:07:23
 *
 */
public class JdbcPoolZJUtil{

    /**
     * @Field: pool
     *          数据库连接池
     */
    private static JdbcPoolZJ pool = new JdbcPoolZJ();

    /**
     * @Method: getConnection
     * @Description: 从数据库连接池中获取数据库连接对象
     * @Anthor:孤傲苍狼
     * @return Connection数据库连接对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{
        return pool.getConnection();
    }

    /**
     * @Method: release
     * @Description: 释放资源，
     * 释放的资源包括Connection数据库连接对象，负责执行SQL命令的Statement对象，存储查询结果的ResultSet对象
     * @Anthor:孤傲苍狼
     *
     * @param conn
     * @param st
     * @param rs
     */
    public static void release(Connection conn, Statement st, ResultSet rs){
        if(rs!=null){
            try{
                //关闭存储查询结果的ResultSet对象
                rs.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;
        }
        if(st!=null){
            try{
                //关闭负责执行SQL命令的Statement对象
                st.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try{
                //关闭Connection数据库连接对象
                pool.returnConnection(conn);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//================================================================================================


    public static class JdbcPoolZJ implements DataSource {
        private static String url = JdbcPropertyLoader.getProperty("jdbc.url");
        private static String username = JdbcPropertyLoader.getProperty("jdbc.username");
        private static String password = JdbcPropertyLoader.getProperty("jdbc.password");
        private static int jdbcPoolInitSize=Integer.parseInt(JdbcPropertyLoader.getProperty("jdbc.poolInitSize"));

        /**
         * @Field: listConnections
         * 使用LinkedList集合来存放数据库链接，
         * 由于要频繁读写List集合，所以这里使用LinkedList存储数据库连接比较合适
         */
        private static LinkedList<Connection> listConnections = new LinkedList<Connection>();

        static {
            try {
                for (int i = 0; i < jdbcPoolInitSize; i++) {
                    Connection conn = DriverManager.getConnection(url, username, password);
                    System.out.println("获取到了链接" + conn);
                    //将获取到的数据库连接加入到listConnections集合中，listConnections集合此时就是一个存放了数据库连接的连接池
                    listConnections.add(conn);
                }

            } catch (Exception e) {
                throw new ExceptionInInitializerError(e);
            }
        }

        @Override
        public PrintWriter getLogWriter() throws SQLException {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void setLogWriter(PrintWriter out) throws SQLException {
            // TODO Auto-generated method stub

        }

        @Override
        public void setLoginTimeout(int seconds) throws SQLException {
            // TODO Auto-generated method stub

        }

        @Override
        public int getLoginTimeout() throws SQLException {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public Logger getParentLogger() throws SQLFeatureNotSupportedException {
            return null;
        }

        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            // TODO Auto-generated method stub
            return false;
        }

        /* 获取数据库连接
         * @see javax.sql.DataSource#getConnection()
         */
        @Override
        public Connection getConnection() throws SQLException {
            //如果数据库连接池中的连接对象的个数大于0
            if (listConnections.size() > 0) {
                //从listConnections集合中获取一个数据库连接
                final Connection conn = listConnections.removeFirst();
                System.out.println("listConnections数据库连接池大小是" + listConnections.size());
                //返回Connection对象的代理对象
                return conn;
            } else {
                throw new RuntimeException("对不起，数据库忙");
            }
        }

        @Override
        public Connection getConnection(String username, String password)
                throws SQLException {
            return null;
        }

        public void returnConnection(Connection conn){
            listConnections.add(conn);
            System.out.println("listConnections数据库连接池大小为" + listConnections.size());

        }
    }
}
